package com.zzptc.zzsgz.bdsjws.services;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.widget.Toast;

import com.socks.library.KLog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zzptc.zzsgz.bdsjws.MyApplication;
import com.zzptc.zzsgz.bdsjws.R;
import com.zzptc.zzsgz.bdsjws.activities.Update2Activity;
import com.zzptc.zzsgz.bdsjws.utils.MyUtils;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

public class MyDownLoadService extends Service {
    NotificationCompat.Builder notifycation;
    NotificationManager notificationManager;
    File  file;
    public MyDownLoadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "服务启动了", Toast.LENGTH_SHORT).show();
        //1.通过intent得到APK的地址
        String uel=null;
        if(intent!=null){
            uel=intent.getStringExtra("aplurl");
        }
        //Toast.makeText(this, uel+"", Toast.LENGTH_SHORT).show();
        //2.创建通知栏
       createNotify();
        //3.首先判断是否存在SD卡   得到文件存储路径
       file= MyUtils.getDir();
        downloadfile(uel,file);//两个参数分别是从哪儿取 放哪儿
        return super.onStartCommand(intent, flags, startId);
    }
    public void downloadfile(String url, final File file){
        //使用OKOkHttpUtils
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"hhh.apk") {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        KLog.i("------",progress);
                        notifycation.setProgress(100,(int)(progress*100),false);
                        notifycation.setContentText("已经下载了"+(int)(progress*100)+"%");
                        notificationManager.notify(0,notifycation.build());
                        super.inProgress(progress, total, id);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        notifycation.setContentText("下载失败");
                        notificationManager.notify(0,notifycation.build());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                    notifycation.setContentText("下载完毕");
                        notifycation.setAutoCancel(true);
                        notificationManager.notify(id,notifycation.build());
                        //安装  点击后安装
                        //installApk(file);
                        Intent intent=MyUtils.getinstallApk(response);
 //                       startActivity(intent);
                        TaskStackBuilder taskStackBuilder=TaskStackBuilder.create(MyDownLoadService.this);
                        taskStackBuilder.addParentStack(Update2Activity.class);
                        taskStackBuilder.addNextIntent(intent);
                        PendingIntent pendingIntent= taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
                        notifycation.setContentIntent(pendingIntent);
                        //让进度条消失
                        notifycation.setProgress(0,0,false);
                        notifycation.setContentText("请点击安装");
                        notifycation.setContentTitle("下载完毕");
                        notificationManager.notify(0,notifycation.build());


                    }
                });

    }
//    public void installApk(File file){
//        Intent intent=new Intent(Intent.ACTION_VIEW);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
//      // MyApplication.getContext().startActivity(intent);
//        startActivity(intent);

   // }
    //创建通知栏     涉及的三个类
    public  void createNotify(){//NotificationManager 状态栏通知管理类 Notification  Notification.Builder//建造者兼容模式
        notificationManager= (NotificationManager) MyApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notifycation=new NotificationCompat.Builder(MyApplication.getContext());
        notifycation.setContentTitle("百度卫士下载")//标题
                .setContentText("正在下载...")//内容
                .setSmallIcon(R.mipmap.ic_logo)//小图标
                .setOngoing(true)
                .setAutoCancel(false);//设置用户不能自动取消
        notificationManager.notify(0,notifycation.build());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
